//
//  ZYDeviceModifyVC.m
//  YiLin
//
//  Created by Zyark on 2018/6/8.
//  Copyright © 2018年 Zyark. All rights reserved.
//

#import "ZYDeviceModifyVC.h"
#import "ZYViewUtils.h"
#import "ZYDevice.h"
#import "ZYHouse.h"
#import "ZYHouseViewModel.h"
#import "ZYDeviceViewModel.h"

@interface ZYDeviceModifyVC ()<UIPickerViewDelegate,UIPickerViewDataSource>
/**
 设备id
 */
@property(nonatomic,strong) UITextField *deviceIdField;

/**
 设备名称
 */
@property(nonatomic,strong) UITextField *deviceNameFiled;

/**
 设备型号
 */
@property(nonatomic,strong) UITextField *modelField;

/**
 设备类型
 */
@property(nonatomic,strong) UITextField *typeField;

/**
 归属
 */
@property(nonatomic,strong) UITextField *homeField;

/**
 所属房间
 */
@property(nonatomic,strong) UITextField *roomField;

/**
 确认按钮
 */
@property(nonatomic,strong) UIButton *confirmBtn;


/**
 类型选择
 */
@property(nonatomic,strong) UIPickerView *typePickerView;

/**
 归属选择
 */
@property(nonatomic,strong) UIPickerView *homePickerView;

/**
 房间选择
 */
@property(nonatomic,strong) UIPickerView *roomPickerView;


/**
 类型
 */
@property(nonatomic,strong) NSArray *typeArray;

/**
 房间类型列表
 */
@property(nonatomic,strong) NSArray *roomArray;

@property(nonatomic,strong) ZYChangeLanguage *language;

@property(nonatomic,strong) ZYHouseViewModel *houseViewModel;

@property(nonatomic,assign) NSInteger houseId;

@property(nonatomic,strong) ZYDeviceViewModel *deviceViewModel;

@property(nonatomic,assign) ZYHomeRoomType roomType;

@end

@implementation ZYDeviceModifyVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.title = [[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_HOME_EDIT_DEVICE_EQUIPMENT_EDITING];
    [self.houseViewModel.indexHouseCommand execute:nil];
}

-(void)setup{
    _language = [ZYChangeLanguage sharedZYChangeLanguage];
    _typePickerView = [self setupPickerView];
    _homePickerView = [self setupPickerView];
    _roomPickerView = [self setupPickerView];
    [self setupView];
    [self setupTap];
    [self bindView];
}

-(UIPickerView *)setupPickerView{
    UIPickerView *pickerView = [[UIPickerView alloc] init];
    //    problemPickerView.size = CGSizeMake(ZYSCREEN_W - left * 2, height);
    pickerView.backgroundColor = [UIColor whiteColor];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    [pickerView reloadAllComponents];
    return pickerView;
}

//初始化视图
-(void)setupView{
    _deviceIdField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_ID] placeholder:@""];
    _deviceNameFiled = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_NAME] placeholder:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_NAME_PLACEHOLDER]];
    _modelField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_MODEL] placeholder:@""];
    _typeField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_TYPE] placeholder:@""];
    _homeField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_HOME] placeholder:@""];
    _roomField = [ZYViewUtils setupTextFieldWithLeftTitle:[_language getStringByKey:LC_DEVICE_EDIT_LABEL_DEVICE_ROOM] placeholder:@""];
    CGFloat padding = 15;
    //设备ID
    [self.view addSubview:_deviceIdField];
    _deviceIdField.top = self.navigationView.bottom +5;
    _deviceIdField.centerX = self.view.centerX;
    _deviceIdField.enabled = NO;
    _deviceIdField.text = self.mac;
    
    //名称
    [self.view addSubview:_deviceNameFiled];
    _deviceNameFiled.top = _deviceIdField.bottom + padding;
    _deviceNameFiled.centerX = self.view.centerX;
    
    //型号
    [self.view addSubview:_modelField];
    _modelField.top = _deviceNameFiled.bottom + padding;
    _modelField.centerX = self.view.centerX;
    
    //类型
    [self.view addSubview:_typeField];
    _typeField.top = _modelField.bottom + padding;
    _typeField.centerX = self.view.centerX;
    [self setRightImageView:_typeField imageName:@"ic_me_info_select"];
    _typeField.inputView = _typePickerView;
    
    //归属
    [self.view addSubview:_homeField];
    _homeField.top = _typeField.bottom + padding;
    _homeField.centerX = self.view.centerX;
    [self setRightImageView:_homeField imageName:@"ic_me_info_select"];
    _homeField.inputView = _homePickerView;
    
    //房间
//    [self.view addSubview:_roomField];
//    _roomField.top = _homeField.bottom + padding;
//    _roomField.centerX = self.view.centerX;
//    _roomField.inputView = _roomPickerView;
//    _roomField.text = [self.roomArray objectAtIndex:_device.roomType];
//    [self setRightImageView:_roomField imageName:@"ic_me_info_select"];
    
    //确认
    _confirmBtn = [ZYViewUtils setupConfirmBtn];
    [self.view addSubview:_confirmBtn];
    _confirmBtn.centerX = self.view.centerX;
    _confirmBtn.top = _homeField.bottom + 25;
    [_confirmBtn addTarget:self action:@selector(doConfirm) forControlEvents:UIControlEventTouchUpInside];
    [_confirmBtn setTitle:[_language getStringByKey:LC_CONFIRM_BUTTON_TITLE] forState:UIControlStateNormal];
    
    if(_device){
        _deviceNameFiled.text = _device.name;
        _modelField.text = _device.model;
        NSLog(@"type:%ld",_device.type);
//        _roomField.text = [self.roomArray objectAtIndex:_device.roomType];
        _roomType = _device.roomType;
        _deviceType = _device.type;
        [_roomPickerView selectRow:_device.roomType inComponent:0 animated:YES];
        [_roomPickerView reloadAllComponents];
    }
    _typeField.text = [self.typeArray objectAtIndex:_deviceType];
    [_typePickerView selectRow:_deviceType inComponent:0 animated:YES];
    [_typePickerView reloadAllComponents];
}

//绑定视图
-(void)bindView{
    @weakify(self);
    //住宅列表
    [[[self.houseViewModel.indexHouseCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        self.homeArray = x;
        NSString *houseId = [ZYConfig houseId];
        [self.homePickerView reloadAllComponents];
        if(NULLString(houseId)){
            ZYHouse *house = [self.homeArray firstObject];
            [ZYConfig setHouseId:[NSString stringWithFormat:@"%ld",house.houseId]];
            self.houseId = house.houseId;
            houseId = [NSString stringWithFormat:@"%ld",house.houseId];
        }else{
            self.houseId = [houseId unsignedIntegerValue];
        }
        NSInteger index = 0;
        for (ZYHouse *item in self.homeArray) {
            if(item.houseId == [houseId unsignedIntegerValue]){
                [self.homePickerView selectRow:index inComponent:0 animated:YES];
                self.homeField.text = item.name;
                break;
            }
            index ++;
        }
    }];
    [self.houseViewModel.indexHouseCommand.errors subscribeNext:^(id x) {
        @strongify(self);
        if([[NSErrorHelper handleErrorMessage:x] isEqualToString:LOGIN_FAILURE]){
            //登录失效
            [ZYBasicHelper handleErrorMessaeWithError:x message:nil controller:self];
        }
    }];
    //编辑设备
    [[[self.deviceViewModel.deviceModifyCommand executionSignals] switchToLatest] subscribeNext:^(id x) {
        @strongify(self);
        [[ToastHelper sharedToastHelper] toastSuccess:[[ZYChangeLanguage sharedZYChangeLanguage] getStringByKey:LC_MODIFY_DEVICE_SUCCESS]];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } error:^(NSError *error) {
        @strongify(self);
        [ZYBasicHelper handleErrorMessaeWithError:error message:[NSErrorHelper handleErrorMessage:error] controller:self];
    }];
    //监听状态
    [[self.deviceViewModel.deviceModifyCommand.executing skip:1] subscribeNext:^(id x) {
        BOOL executing = [x boolValue];
        [[ToastHelper sharedToastHelper] setSimleProgressVisiable:executing];
    }];
}

/**
 设置右视图
 @param textField texField
 @param imageName 显示的图片
 */
-(void)setRightImageView:(UITextField *)textField imageName:(NSString *)imageName{
    UIImageView *rightImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]];
    rightImageView.frame = CGRectMake(0, 0, 16, 10);
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYSCREEN_W * 0.08, ZYSCREEN_W * 0.26)];
    [rightView addSubview:rightImageView];
    rightImageView.centerY = rightView.centerY;
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.rightView = rightView;
}

-(void)doConfirm{
    self.deviceViewModel.mac = self.mac;
    self.deviceViewModel.roomType = ZYHomeRoomTypeBedroom;
    self.deviceViewModel.name = _deviceNameFiled.text;
    self.deviceViewModel.deviceType = _deviceType;
    self.deviceViewModel.model = _modelField.text;
    self.deviceViewModel.houseId = self.houseId;
    self.deviceViewModel.isModify = self.isModify;
    [self.deviceViewModel.deviceModifyCommand execute:nil];
}

#pragma mark - UIPickerViewDelegate UIPickerViewDataSource
//返回有几列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

//返回指定列的行数
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(pickerView == _typePickerView){
        return [self.typeArray count];
    }else if(pickerView == _homePickerView){
        return [self.homeArray count];
    }else{
        return [self.roomArray count];
    }
    
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if(pickerView == _typePickerView){
        return [self.typeArray objectAtIndex:row];
    }else if(pickerView == _homePickerView){
        ZYHouse *house = [self.homeArray objectAtIndex:row];
        return house.name;
    }else{
        return [self.roomArray objectAtIndex:row];
    }
}


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if(pickerView == _typePickerView){
        [_typeField resignFirstResponder];
        _typeField.text = [self.typeArray objectAtIndex:row];
        switch (row) {
            case 0:
                _deviceType = ZYDeviceTypeAirConditioning;
                break;
            case 1:
                _deviceType = ZYDeviceTypeRadiantFloorHeating;
                break;
            case 2:
                _deviceType = ZYDeviceTypeVentilationSystem;
                break;
            default:
                break;
        }
    }else if(pickerView == _homePickerView){
        [_homeField resignFirstResponder];
        ZYHouse *house = [self.homeArray objectAtIndex:row];
        _homeField.text = house.name;
        self.houseId = house.houseId;
    }else{
        [_roomField resignFirstResponder];
        _roomField.text = [self.roomArray objectAtIndex:row];
        switch (row) {
            case 0:
                _roomType = ZYHomeRoomTypeLivingRoom;
                break;
            case 1:
                _roomType = ZYHomeRoomTypeBedroom;
                break;
            case 2:
                _roomType = ZYHomeRoomTypeChildrenRoom;
                break;
            default:
                break;
        }
    }
    
}


#pragma mark - Getter
-(NSArray *)roomArray{
    if(!_roomArray){
        _roomArray = @[[_language getStringByKey:LC_INDEX_MAIN_LIVING_ROOM_LABEL],
                       [_language getStringByKey:LC_INDEX_MAIN_BEDROOM_LABEL],
                       [_language getStringByKey:LC_INDEX_MAIN_CHILDREN_ROOM_LABEL]];
    }
    return _roomArray;
}

-(NSArray *)typeArray{
    if(!_typeArray){
        _typeArray = @[[_language getStringByKey:LC_DEVICE_TYPE_AIR_CONDITIONING],
                       [_language getStringByKey:LC_DEVICE_TYPE_RADIANT_FLOOR_HEATING],
                       [_language getStringByKey:LC_DEVICE_TYPE_VENTILATION_SYSTEM]];
    }
    return _typeArray;
}

-(ZYHouseViewModel *)houseViewModel{
    if(!_houseViewModel){
        _houseViewModel = [[ZYHouseViewModel alloc] init];
    }
    return _houseViewModel;
}

-(ZYDeviceViewModel *)deviceViewModel{
    if(!_deviceViewModel){
        _deviceViewModel = [[ZYDeviceViewModel alloc] init];
    }
    return _deviceViewModel;
}

@end
